﻿using AutoMapper;
using FI.EntityFramework;
using Sample.BusinessEntities;
using Sample.Common;
using Sample.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sample.DataAccess
{
    public class PersonDA : Repository<Person, ApplicationContext>
    {
        public PersonDA()
            : base(new ApplicationContext())
        {

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Person, PersonModel>().ReverseMap();

            });

        }

        public IEnumerable<int> GetIDs()
        {
            var query = this.DbContext.People.Select(n => n.Id).ToList();

            return query;
        }

        public PersonModel GetPerson(int id)
        {
            return this.DbContext.People.Where(n => n.Id == id).ProjectToSingle<PersonModel>();
        }

        public IEnumerable<PersonModel> GetPersonsByCriteria(string name, DateTime? birthdate, int page, out int totalCount)
        {
            var query = this.DbContext.People.WhereIf(!string.IsNullOrEmpty(name), n => n.Name == name).WhereIf(birthdate.HasValue, n => n.BirthDate == birthdate);

            totalCount = query.Count();

            return query.GetPageableData(Constants.PageSize, page, "CreatedTime", true).Select(n => Mapper.Map<PersonModel>(n)).ToList();

        }

        public IEnumerable<PersonModel> GetPersons()
        {
            return this.DbContext.People.ProjectToList<PersonModel>();
        }

        public void AddPerson(PersonModel personModel)
        {
            var person = Mapper.Map<Person>(personModel);

            MarkAsAdded(person);

            DbContext.SaveChanges();
        }
        public void UpdatePerson(PersonModel personModel)
        {

            var person = Mapper.Map<Person>(personModel);

            MarkAsModified(person);

            DbContext.SaveChanges();
        }
        public void UpdateNameOfPerson(PersonModel personModel)
        {
            var person = Mapper.Map<Person>(personModel);

            MarkAsModifiedPartial(person, n => n.Name);

            // MarkAsModified(person);

            DbContext.SaveChanges();
        }
    }
}
